package com.iut.projectandroid;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.NumberPicker;
import android.widget.Spinner;

import com.iut.model.BusinessLayer;
import com.iut.utils.FileHelper;
import com.iut.utils.MenuHelper;

public class ParcelAddActivity extends Activity
{
	private EditText name;

	private NumberPicker surface;
	
	private String culture;
	
	private String culturePrec;
	
	private ImageView imagePreview;
	
	private byte[] imageData;
	
	private EditText addressText;
	
	LocationManager locationManager;
	
	private double latitude;
	
	private double longitude;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.activity_parcel_add);
		
		addressText = (EditText) findViewById(R.id.edit_text_address);
		
		if(savedInstanceState != null)
		{
			imageData = savedInstanceState.getByteArray("IMAGE_BYTE");
			latitude = savedInstanceState.getDouble("LATITUDE");
			longitude = savedInstanceState.getDouble("LONGITUDE");
		}
		
		imagePreview = (ImageView) findViewById(R.id.preview_photo);
		
		Button takePhotoButton = (Button) findViewById(R.id.take_photo_button);
		
		takePhotoButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) 
			{
				Intent i = new Intent(getApplicationContext(), CameraActivity.class);				
				startActivityForResult(i, CameraActivity.TAKE_PHOTO);
			}
		});
		
		name = (EditText) findViewById(R.id.name_edit);
		
		Spinner spinner1 = (Spinner) findViewById(R.id.culture_edit);
		Spinner spinner2 = (Spinner) findViewById(R.id.cult_prec_edit);
		
		ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getApplicationContext(), R.array.spin_values, android.R.layout.simple_spinner_dropdown_item);
		
		spinner1.setAdapter(adapter);
		spinner2.setAdapter(adapter);
		
		OnItemSelectedListener listener = new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int pos, long id) 
			{
				
				switch (arg0.getId())
				{
					case R.id.culture_edit: culture = (String) arg0.getItemAtPosition(pos);
						
						break;
						
					case R.id.cult_prec_edit: culturePrec = (String) arg0.getItemAtPosition(pos);
						
						break;
	
					default:
						break;
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {}
		};
		
		spinner1.setOnItemSelectedListener(listener);
		spinner2.setOnItemSelectedListener(listener);
		
		surface = (NumberPicker) findViewById(R.id.surface_picker);
		surface.setMinValue(0);
		surface.setMaxValue(20);
		
		Button add = (Button) findViewById(R.id.button_add);
		add.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) 
			{
				String nameValue = name.getText().toString();
				int surfaceValue = surface.getValue();
				String path = FileHelper.saveFile(imageData);
				
				BusinessLayer.addParcelle(getApplicationContext(), nameValue, culture, culturePrec, surfaceValue,
						path, latitude, longitude, addressText.getText().toString()); 
				addParcelDone();
			}
		});
		
		ImageButton locationButton = (ImageButton) findViewById(R.id.button_loc);
		
		locationManager = (android.location.LocationManager) ParcelAddActivity.this.getSystemService(Context.LOCATION_SERVICE);
		
		locationButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) 
			{
				locationManager.requestLocationUpdates(android.location.LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
				locationManager.requestLocationUpdates(android.location.LocationManager.GPS_PROVIDER, 0, 0, locationListener);
			}
		});
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) 
	{
		if(resultCode == RESULT_OK)
		{
			switch (requestCode)
			{
				case CameraActivity.TAKE_PHOTO : getPictureFromIntent(data);
					
					break;
	
				default:
					break;
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	private void getPictureFromIntent(Intent data) 
	{
		imageData = data.getByteArrayExtra("PICTURE_DATA");
	}
	
	@Override
	protected void onSaveInstanceState(Bundle outState) 
	{
		outState.putByteArray("IMAGE_BYTE", imageData);
		outState.putDouble("LATITUDE", latitude);
		outState.putDouble("LONGITUDE", longitude);
		super.onSaveInstanceState(outState);
	}
	
	@Override
	protected void onResume() 
	{
		if(imageData != null && imageData.length != 0)
		{
			InputStream stream = new ByteArrayInputStream(imageData);
			
			imagePreview.setImageDrawable(Drawable.createFromStream(stream, "preview"));
		}
		
		super.onResume();
	}

	private void addParcelDone() 
	{
		setResult(RESULT_OK);
		finish();
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.alternative, menu);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) 
	{
		if(MenuHelper.launchActivity(this ,getApplicationContext(), item.getItemId()))
		{
			return true;
		}
		else
		{
			return super.onOptionsItemSelected(item);
		}
	}
	
	LocationListener locationListener = new LocationListener() {
		
		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) { }
		
		@Override
		public void onProviderEnabled(String provider) { }
		
		@Override
		public void onProviderDisabled(String provider) { }
		
		@Override
		public void onLocationChanged(Location location) 
		{
			try 
			{
				String address = getAddress(location.getLatitude(), location.getLongitude());
				addressText.setText(address);
				locationManager.removeUpdates(locationListener);
			} 
			catch (IOException e) { }
		}
	};
	
	public String getAddress(double latitude, double longitude) throws IOException
	{
		this.latitude = latitude;
		
		this.longitude = longitude;
		
		Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.FRANCE);
		
		List<Address> addressList = geocoder.getFromLocation(latitude, longitude, 1);
		
		Address address = addressList.get(0);
		
		String street = address.getThoroughfare();
		
		String postalCode = address.getPostalCode();
		
		String city = address.getLocality();
		
		String sAddr = String.format("%s %s %s", street, postalCode, city);
		
		return sAddr;
	}
}
